package com.ny.demo523;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
   Connection connection = SqlConnection.getCon();
   public UserDao() throws  SQLException, ClassNotFoundException {
      
   }



    public int addUser(String username, String password) throws SQLException, ClassNotFoundException {
        // 1. 连接数据库
        Connection connection = SqlConnection.getCon();

        // 2. 编写sql语句
        String sql = "insert into users(username,password) values(?,?)";

        // 3. 执行sql语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql); // 预编译sql语句给问号进行赋值
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);

        // 4. 返回影响的行数
        return preparedStatement.executeUpdate();
    }
    public Users login(String username, String password) throws SQLException, ClassNotFoundException {
        Users users = null;
        int i = 1;
        // 1. 连接数据库
        Connection connection = SqlConnection.getCon();
        // 2. 编写 sql 语句
        String sql = "select * from users where username=? and password=?";
        // 4. 执行 sql 语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 给问号赋值。1 表示第一个问号，输入的用户名给第一个问号。2 表示第二个问号，输入的密码给第二个问号。
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        // 5. 接收执行 sql 语句的结果，查询的结果是放在 resultSet 中的.
        ResultSet resultSet = preparedStatement.executeQuery();
        // 6. 把查询的结果 resultSet 交给 Users，通过 set 方法把查询出来的结果交给 users 对象
        if (resultSet.next()) {
            users = new Users();
            users.setId(resultSet.getInt("id"));
            users.setUsername(resultSet.getString("username"));
            users.setPassword(resultSet.getString("password"));
        }
        return users;
    }
    public int deleteUsers(int id) throws SQLException, ClassNotFoundException {
       String sql = "delete from users where id = ?";
       PreparedStatement preparedStatement = connection.prepareStatement(sql);
       preparedStatement.setInt(1,id);
       return preparedStatement.executeUpdate();
    }
   // 修改
    public int updateUsers(int id, String username, String password) throws SQLException, ClassNotFoundException {
       String sql = "update users set username = ?,password = ? where id = ?";
       PreparedStatement preparedStatement = connection.prepareStatement(sql);
       preparedStatement.setString(1,username);
       preparedStatement.setString(2,password);
       preparedStatement.setInt(3,id);
       return preparedStatement.executeUpdate();
    }


}


